<template>
    <div class="content" 
        ref="broadcastContainer"
        v-draggable-resizable="{
            storageKey: 'broadcast',
            controlPosition: 'top',
            hideHintText: '击杀播报'
        }"
        @mouseenter="handleMouseEnter"
        @mouseleave="handleMouseLeave">
        
        <!-- 演示模式切换按钮 -->
        <div v-show="showDemoButton" 
             class="demo-toggle" 
             @click="toggleDemo"
             @mouseenter="handleMouseEnter"
             @mouseleave="handleMouseLeave">
            <span>{{ isInternalDemo ? '退出演示' : '演示模式' }}</span>
        </div>
        
        <!-- 内容容器 - 有数据或演示模式时显示 -->
        <div v-show="showBroadcast || isInternalDemo" class="broadcast-content">
            <div class="avatar-container left">
                <span class="avatar" :style="{ background: currentActiveMessage.killer.team }">
                    <img :src="currentActiveMessage.killer.avatar" alt="头像" />
                </span>
                <span class="nickname">{{ currentActiveMessage.killer.name }}</span>
            </div>
            <span class="txt">{{ killBroadcastArr.at(currentActiveMessage.killVoice).txt }}</span>
            <div class="avatar-container right" :class="{ shake: showBroadcast }">
                <span class="avatar" :style="{ background: currentActiveMessage.victim.team }">
                    <img :src="currentActiveMessage.victim.avatar" alt="avatar" />
                </span>
                <img class="defeat" src="../assets/defeat.png">
                <span class="nickname">{{ currentActiveMessage.victim.name }}</span>
            </div>
        </div>
    </div>
    <audio ref="audioRefs" v-for="item in killBroadcastArr" preload="auto">
        <source :src="item.voice" type="audio/wav">
    </audio>
</template>

<script setup>
import { onMounted, ref, defineProps, computed } from 'vue';
import eventBus from 'vue3-eventbus';

import First_Blood from '@/assets/killVoice/First Blood.wav'
import Double_Kill from '@/assets/killVoice/Double Kill.wav'
import Triple_kill from '@/assets/killVoice/Triple kill.wav'
import Ultra_kill from '@/assets/killVoice/Ultra kill.wav'
import Rampage from '@/assets/killVoice/Rampage.wav'
import Killing_Spree from '@/assets/killVoice/Killing Spree.wav'
import Dominating from '@/assets/killVoice/Dominating.wav'
import Mega_Kill from '@/assets/killVoice/Mega Kill.wav'
import Unstoppable from '@/assets/killVoice/Unstoppable.wav'
import Monster_Kill from '@/assets/killVoice/Monster Kill.wav'
import Godlike from '@/assets/killVoice/Godlike.wav'
import Holy_Shit from '@/assets/killVoice/Holy Shit.wav'

const props = defineProps(['leftPlayer', 'rightPlayer']);
const messageQueue = ref([]);
const activeMessage = ref({});
const isProcessMessage = ref(false);
const showBroadcast = ref(false);

// 组件引用
const broadcastContainer = ref(null);

// 内部演示模式状态
const isInternalDemo = ref(false);
const showDemoButton = ref(false);
let hideButtonTimer = null;

// 切换演示模式
const toggleDemo = () => {
    isInternalDemo.value = !isInternalDemo.value;
};

// 显示演示按钮
const handleMouseEnter = () => {
    if (hideButtonTimer) {
        clearTimeout(hideButtonTimer);
        hideButtonTimer = null;
    }
    showDemoButton.value = true;
};

// 延迟隐藏演示按钮
const handleMouseLeave = () => {
    hideButtonTimer = setTimeout(() => {
        showDemoButton.value = false;
    }, 300); // 300ms延迟
};
const killBroadcastArr = [
    { voice: First_Blood, txt: '第一滴血' },
    { voice: '', txt: '击败' },
    { voice: Double_Kill, txt: '双杀' },
    { voice: Triple_kill, txt: '三杀' },
    { voice: Ultra_kill, txt: '四杀' },
    { voice: Rampage, txt: '五杀' },
    { voice: Killing_Spree, txt: '大杀特杀' },
    { voice: Dominating, txt: '主宰比赛' },
    { voice: Mega_Kill, txt: '杀人如麻' },
    { voice: Unstoppable, txt: '无人能挡' },
    { voice: Monster_Kill, txt: '变态杀戮' },
    { voice: Godlike, txt: '如同神一般' },
    { voice: Holy_Shit, txt: '超越神的杀戮' },
];
const audioRefs = ref([]); // 定义 ref 数组存储音频元素

// 演示数据
const demoMessage = {
    killVoice: 2, // 双杀
    killer: {
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        name: '演示击杀者',
        id: "demo001",
        team: 'red'
    },
    victim: {
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        name: '演示被击杀者',
        id: "demo002",
        team: 'blue'
    },
};

// 根据演示模式选择数据源
const currentActiveMessage = computed(() => {
    if (isInternalDemo.value) {
        return demoMessage;
    }
    
    // 确保 activeMessage 有完整的结构
    if (!activeMessage.value || !activeMessage.value.killer || !activeMessage.value.victim) {
        return {
            killVoice: 1,
            killer: {
                avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
                name: '默认玩家',
                id: "default001",
                team: 'blue'
            },
            victim: {
                avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
                name: '默认玩家',
                id: "default002",
                team: 'red'
            },
        };
    }
    
    return activeMessage.value;
});

// 检查组件是否被隐藏
const isComponentVisible = () => {
    if (!broadcastContainer.value) return true;
    
    // 检查是否有隐藏相关的类名
    const classList = broadcastContainer.value.className;
    return !classList.includes('dr-hidden-');
};

// 播放音频
const playAudio = (index) => {
    // 如果组件被隐藏，不播放音频
    if (!isComponentVisible()) {
        console.log('组件已隐藏，跳过音频播放');
        return;
    }
    
    if (index == 1 || index == 2 || index == 3 || index == 4) return; 
    const audio = audioRefs.value[index];
    if (audio) {
        audio.click();
        audio.play().catch((err) => {
            // 静默处理浏览器自动播放策略错误，这是正常的安全限制
            if (err.name === 'NotAllowedError') {
                // 浏览器禁止自动播放，这是正常的，不需要报错
                return;
            }
            // 只有非自动播放策略的其他错误才输出到控制台
            console.error('音频播放失败:', err);
        });
    }
};

// 停止播放音频
const stopAudio = (index) => {
    const audio = audioRefs.value[index];
    if (audio) {
        audio.pause(); // 暂停音频
        audio.currentTime = 0; // 将播放进度重置为起点
    }
};

// 获取音频总时长
const getAudioDuration = (index) => {
    
    return new Promise((resolve) => {
        if (index == 1 || index == 2 || index == 3 || index == 4) resolve(1); 
        const audio = audioRefs.value[index];
        if (audio) {
            // 如果元数据已经加载，可以直接获取 duration
            if (!isNaN(audio.duration) && audio.duration > 0) {
                resolve(audio.duration);
            } else {
                // 等待元数据加载完成
                audio.addEventListener('loadedmetadata', () => {
                    console.log(`音频 ${index} 的总时长为: ${audio.duration} 秒`);
                    resolve(audio.duration);
                });
            }
        }
    });
};

const initActiveMessage = () => {
    activeMessage.value = {
        killVoice: 1,
        killer: {
            avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            name: '测试用昵称【蓝方玩家】',
            id: "0001",
            team: 'blue'
        },
        victim: {
            avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            name: '测试用昵称【红方玩家】',
            id: "0001",
            team: 'red'
        },
    }
}

const handleProcessMessage = async () => {
    isProcessMessage.value = true;
    activeMessage.value = messageQueue.value.shift();
    activeMessage.value.killer.team = findTeam(activeMessage.value.killer.id);
    activeMessage.value.victim.team = findTeam(activeMessage.value.victim.id);
    showBroadcast.value = true;

    let duration = await getAudioDuration(activeMessage.value.killVoice);
    playAudio(activeMessage.value.killVoice);

    setTimeout(() => {
        showBroadcast.value = false;
        stopAudio(activeMessage.value.killVoice);
        setTimeout(() => {
            if (messageQueue.value.length > 0) {
                handleProcessMessage();
            } else {
                isProcessMessage.value = false;
            }
        }, 200);
    }, duration * 1000);
};

const findTeam = (id) => {
    if (props.leftPlayer.length <= 0 || props.rightPlayer.length <= 0) return 'black';

    if (props.leftPlayer.findIndex(item => item.player_id === id) != -1) {
        return 'blue';
    }

    if (props.rightPlayer.findIndex(item => item.player_id === id) != -1) {
        return 'red';
    }

    return 'black';
}

onMounted(() => {
    // 初始化默认消息
    initActiveMessage();
    
    eventBus.on('socket-message', message => {
        if (message.type == 'clearBroadcast') {
            showBroadcast.value = false;
            messageQueue.value = []
            if (activeMessage.value && activeMessage.value.killVoice !== undefined) {
                stopAudio(activeMessage.value.killVoice);
            }
            initActiveMessage();
        }
        if (message.type != 'broadcast') return;
        messageQueue.value.push(message);
        
        if (isProcessMessage.value == false) {
            handleProcessMessage();
        }
    });
});
</script>

<style lang="less" scoped>
.content {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-height: 50px;
    min-width: 200px;
    position: fixed;
    top: 30px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    border-radius: 50px;
    
    .broadcast-content {
        display: inline-flex;
        align-items: start;
        justify-content: space-between;
        height: 50px;
        background: linear-gradient(
            0deg,
            rgba(206, 56, 56, 0.7) 0%,
            rgba(150, 150, 150, 0.3) 90%
        );
        border-radius: 50px;
    }
    
    .empty-state {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 50px;
        width: 200px;
        background: rgba(100, 100, 100, 0.3);
        border: 2px dashed rgba(255, 255, 255, 0.5);
        border-radius: 25px;
        
        .empty-text {
            color: rgba(255, 255, 255, 0.7);
            font-size: 14px;
            text-align: center;
        }
    }
    
    .avatar-container {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;

        &.shake {
            animation: shake .2s ease-in-out;
        }

        .nickname {
            position: absolute;
            bottom: -20px;
            margin-top: 5px;
            font-size: 14px;
            color: #fff;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
            word-break: break-word;
            text-align: center;
            height: 14px;
            width: 100px;
            line-height: 14px;
        }

        .defeat {
            position: absolute;
            top: 13px;
            right: -16px;
            width: 0;
            height: 20px;
            z-index: 100;
            transform: rotate(45deg);
            transform-origin: center;
            opacity: 0.7;
            animation: expandWidth .2s forwards;
        }
    }

    .avatar {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        height: 50px;
        width: 50px;
        border-radius: 50%;
        overflow: hidden;
        position: relative;
        
        img {
            height: 85%;
            width: 85%;
            border-radius: 50%;
            object-fit: cover;
        }
    }

    .txt {
        display: inline-block;
        height: 50px;
        width: 150px;
        line-height: 50px;
        text-align: center;
        color: #ffd700;
        font-size: 15px;
        font-weight: bold;
        text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
    }
}

@keyframes shake {
    0%, 100% {
        transform: translateX(0);
    }
    25% {
        transform: translateX(-5px);
    }
    50% {
        transform: translateX(5px);
    }
    75% {
        transform: translateX(-5px);
    }
}

@keyframes expandWidth {
    from {
        width: 0;
    }
    to {
        width: 80px;
    }
}

// 演示模式切换按钮
.demo-toggle {
    position: absolute;
    top: -40px;
    right: 10px;
    background: rgba(255, 165, 0, 0.8);
    color: white;
    padding: 6px 16px;
    border-radius: 16px;
    font-size: 12px;
    cursor: pointer;
    user-select: none;
    z-index: 1010;
    border: 2px solid #ff8c00;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    
    &:hover {
        background: rgba(255, 140, 0, 0.9);
        border-color: #e07600;
    }
}
</style>